package com.example.chat.service.impl;

import com.example.common.common.config.llm.RedisMemoryRepository;
import com.example.common.common.enums.ChatTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import com.example.chat.service.FileChatService;
import com.example.chat.tool.AITool;
import com.example.chat.tool.ToolExecutor;


/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/3 10:14
 **/
@Service
@RequiredArgsConstructor
public class AIService {

    private final ChatClient chatClient;
    private final ToolExecutor toolExecutor;
    private final FileChatService fileChatService;

    public String process(String requestContent, String chatId, ChatTypeEnum chatTypeEnum) {
        if (chatTypeEnum == null) {
            // 1. 意图识别 获取prompt 和 Tool
            if (requestContent.contains("天气")) {
                chatTypeEnum = ChatTypeEnum.WEATHER;
            } else if (requestContent.contains("文件中")){
                chatTypeEnum = ChatTypeEnum.FILE_CHAT;
                requestContent = fileChatService.getSimilaritySearch(chatId, requestContent);
            }
            // 枚举为空，默认对话模型
            if (chatTypeEnum == null) {
                chatTypeEnum = ChatTypeEnum.CHAT;
            }
        }

        // 根据枚举获取prompt 和 tool
        String prompt = chatTypeEnum.getPrompt();
        AITool tool = null;
        if (chatTypeEnum.getToolName() != null) {
            tool =  toolExecutor.executeTool(chatTypeEnum.getToolName());
        }

        // 2. 调用AI functionCalling
        ChatClient.ChatClientRequestSpec builder = chatClient.prompt(prompt)
                .user(requestContent)
                .advisors(a -> a.param(RedisMemoryRepository.CONVERSATION_ID, chatId));
        if (tool != null) {
            builder = builder.tools(tool);
        }
        return builder.call().content();
    }

}